package com.headwind.logistics.common.error;

import com.headwind.logistics.common.util.RestResult;
import com.headwind.logistics.common.util.ResultCode;
import com.headwind.logistics.common.util.ResultGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author 小恶魔
 * @Date 2020-07-16 19:54
 * @Version 1.0
 * @DESCRIPTION 自定义全局异常处理类
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //接口信息生成工具
    @Resource
    private ResultGenerator resultGenerator;

    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = ControllerException.class)
    @ResponseBody
    public RestResult bizExceptionHandler(HttpServletRequest req, ControllerException e){
        logger.error("发生业务异常！原因是：{}",e.getErrorMsg());
        return resultGenerator.getFreeResult(e.getErrorCode(),e.getMessage(),null);
    }

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public RestResult exceptionHandler(HttpServletRequest req, NullPointerException e){
        logger.error("发生空指针异常！原因是:",e);
        return resultGenerator.getFreeCodeMessage(ResultCode.INTERNAL_SERVER_ERROR,"不可为空哦");
    }


    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public RestResult exceptionHandler(HttpServletRequest req, Exception e){
        logger.error("未知异常！原因是:",e);
        return resultGenerator.getFreeCodeMessage(ResultCode.INTERNAL_SERVER_ERROR,"服务器内部错误");
    }
}
